# coding:utf-8
"""
description:Add Device list Page和 Add Device 详情页操作，不包括实际device操作
"""
import os, random, time

from appium.webdriver.common import mobileby

from common.Gesture_Mainpulation import gesture_mainpulation
from common.Get_Yaml import get_yaml
from common.Log import LOG
from config.GlobalParameter import TEST_Element_YAML
from pages.Dashboard_page import dashboard_page

TaskDevice_Data = get_yaml(os.path.join(TEST_Element_YAML, 'Devices', 'AddDevice.yaml'))


class AddDevice_page(dashboard_page):
    by = mobileby.MobileBy()

    """点击或获取Hub，Switches，Plugs，Sensors，Buttons，Curtain and Roller Blind、
    Lightings，Smart Station，IR Remote Control，Bluetooth一行"""
    AddListDeviceName_loc = (by.ID, TaskDevice_Data.get_elementInfo(0))

    def get_AddListDeviceName(self):
        """点击或获取Hub，Switches，Plugs，Sensors，Buttons，Curtain and Roller Blind
        ，Lightings，Smart Station，IR Remote Control，Bluetooth一行"""
        return self.find_elements(*self.AddListDeviceName_loc)

    """1,点击Smart Hub、1|2|3-Gang Light Switch UK|US、三个sensor、Button、Dimmer Switch US|UK,Smart Plug UK|US、
    3.5kW High Power Switch、Curtain、Roller Blind、Ceiling Light、Station和Station Lite，Add Device弹框元素见Public.yaml（1）
    2,Smart plug 和 3.5kw hight power 点击后出现‘Warning’框，点击弹框OK按钮见Public.yaml（6）"""
    CeilingSunset_loc = (by.ID, TaskDevice_Data.get_elementInfo(1))

    def get_SelectDeviceToPair(self):
        """1,点击Smart Hub、1|2|3-Gang Light Switch UK|US、三个sensor、Button、Dimmer Switch US|UK,Smart Plug UK|US、
        3.5kW High Power Switch、Curtain、Roller Blind、Ceiling Light、Station和Station Lite，Add Device弹框元素见Public.yaml（1）
        2,Smart plug 和 3.5kw hight power 点击后出现‘Warning’框，点击弹框OK按钮见Public.yaml（6）"""
        return self.find_elements(*self.CeilingSunset_loc)

    # 全部device page，‘LED is not blinking?’链接点击后弹框
    ErrorLEDNot_loc = (by.ID, TaskDevice_Data.get_elementInfo(2))

    def click_ErrorLEDNot(self):
        """全部device page，‘LED is not blinking?’链接点击后弹框"""
        self.find_element(*self.ErrorLEDNot_loc).click()

    # 获取‘LED is not blinking?’》弹框文字/tvPairDeviceReset2是滑动后NOTE
    PairDeviceNote_loc = (by.ID, TaskDevice_Data.get_elementInfo(3))

    def get_PairDeviceNote(self):
        """获取‘LED is not blinking?’》弹框文字/tvPairDeviceReset2是滑动后NOTE"""
        return self.find_element(*self.PairDeviceNote_loc).text

    # 和2，3，4属于一个弹框,获取‘LED is not blinking?’弹框文字或者进行滑动出现note文字
    PairDeviceText_loc = (by.ID, TaskDevice_Data.get_elementInfo(18))

    def swipe_PairDeviceText(self):
        """和2，3，4属于一个弹框,获取‘LED is not blinking?’弹框文字或者进行滑动出现note文字"""
        gesture_mainpulation().swipe_up(self.driver, self.find_element(*self.PairDeviceText_loc))

    # 点击‘LED is not blinking?’弹框的ok按钮
    PairDeviceOK_loc = (by.ID, TaskDevice_Data.get_elementInfo(4))

    def click_PairDeviceOK(self):
        """点击‘LED is not blinking?’弹框的ok按钮"""
        self.find_element(*self.PairDeviceOK_loc).click()

    def func_GetNote(self):
        """
        点击‘LED is not blinking?’后滑动弹框，返回文字
        :return:
        """
        self.click_ErrorLEDNot()
        # self.swipe_PairDeviceText()   #获取元素为/tvPairDeviceReset2需要滑动后获取NOTE文字
        return self.get_PairDeviceNote()

    """1，wifi》 Smart hub和Smart plug显示为SCAN QR CODE，点击后的弹框按钮见Public.yaml（0，1）
    2，zigbee》switches、dimmers、3.5kw poer、there sensor and button Zigbee设备页面显示为Pair """
    btnAddDevicePair_loc = (by.ID, TaskDevice_Data.get_elementInfo(5))

    def click_btnAddDevicePair(self):
        """
        1，wifi》 Smart hub和Smart plug显示为SCAN QR CODE，点击后的弹框按钮见Public.yaml（0，1）
        2，zigbee》switches、dimmers、3.5kw poer、there sensor and button Zigbee设备页面显示为Pair
        :return:
        """
        self.find_element(*self.btnAddDevicePair_loc).click()

    # Smart hub和Smart plug，根据ScanQR界面断言
    csvScanQR_loc = (by.ID, TaskDevice_Data.get_elementInfo(6))

    def assertVisible_ScanQR(self):
        """Smart hub和Smart plug，根据ScanQR界面断言"""
        return super().assertVisible(*self.csvScanQR_loc)

    def func_ScanAndPair(self):
        """hub和plug时点击‘Scan QR code’按钮。zigbee设备时点击pair按钮。
        1,手机链接5g网络，出现弹框随机点击continue或OK按钮。
        2,为2.4g，直接跳转zigbee设备添加过程页"""
        LOG.info(
            "点击Hub、Plug的‘Scan QR code’按钮。点击switches、dimmers、there sensor and button的‘Pair’按钮")
        self.click_btnAddDevicePair()
        if super().assertVisible_confirm():  # 判断手机是否链接为5g网络
            if random.randint(1, 2) == 1:
                LOG.info("'Your phone is currently connected to a 5Ghz Network'》》》点击continue按钮。。。")
                super().click_cancel()  # continue
                return self.assertVisible_ScanQR()
            else:
                LOG.info("'Your phone is currently connected to a 5Ghz Network'》》》点击OK关闭弹框按钮。。。")
                super().click_confirm()  # 点击ok按钮关闭弹框
                return True
        else:
            if self.assertVisible_ScanQR():
                LOG.info("判断为Hub、Plug添加详情页。。。")
                return True
            else:
                LOG.info("跳转zigbee设备添加过程页。根据页面信息内容断言。。。")
                return self.assertVisible_ProgressMsg()

    # 点击‘SEARCH WIFI DEVICE’按钮，弹框
    btnAddDeviceSearch_loc = (by.ID, TaskDevice_Data.get_elementInfo(7))

    def click_btnAddDeviceSearch(self):
        """点击‘SEARCH WIFI DEVICE’按钮，弹框"""
        self.find_element(*self.btnAddDeviceSearch_loc).click()

    # 获取弹框内容‘If the device is not found, open WiFi settings……’断言，弹框关闭按钮见Public.yaml（3）
    textTips_loc = (by.ID, TaskDevice_Data.get_elementInfo(8))

    def assertVisible_textTips(self):
        """获取弹框内容‘If the device is not found, open WiFi settings……’断言，弹框关闭按钮见Public.yaml（3）"""
        return super().assertVisible(*self.textTips_loc)

    def func_AddDeviceSearch(self):
        """
        点击WIFI设备的‘SEARCH WIFI DEVICE’按钮，
         1,手机链接5g网络，出现弹框随机点击continue或OK按钮。
        2,为2.4g，直接跳转zigbee设备添加过程页
        :return:
        """
        LOG.info("点击Hub、Plug、3.5kW Switch、Curtain、Blind、Ceiling Light、Station和Lite的‘SEARCH WIFI DEVICE’按钮")
        self.click_btnAddDeviceSearch()
        if super().assertVisible_confirm():  # 判断手机是否链接为5g网络
            LOG.info("'Your phone is currently connected to a 5Ghz Network'》》》点击continue或OK关闭弹框按钮")
            if random.randint(1, 2) == 1:
                super().click_cancel()  # 点击ok按钮关闭弹框
                return True
            else:
                super().click_cancel()  # continue
                return self.assertVisible_textTips()
        else:  # 判断手机链接2.4ghz 网络
            LOG.info("手机正确链接2.4Ghz网络，search wifi device 断言---%s" % self.find_element(*self.textTips_loc).text)
            return self.assertVisible_textTips()

    # 获取ssid text并点击跳转页面
    Ssid_loc = (by.ID, TaskDevice_Data.get_elementInfo(9))

    def get_Ssid(self):
        """获取ssid text并点击跳转页面"""
        return self.find_element(*self.Ssid_loc)

    # witches、dimmers、3.5kw power、there sensor and button Zigbee设备添加过程页面根据元素内容断言
    ProgressMsg_loc = (by.ID, TaskDevice_Data.get_elementInfo(10))

    def assertVisible_ProgressMsg(self):
        """witches、dimmers、3.5kw power、there sensor
        and button Zigbee设备添加过程页面根据元素内容断言"""
        return super().assertVisible(*self.ProgressMsg_loc)

    # SELECT A SMART HUB page》获取Hub name
    SelectHubToName_loc = (by.ID, TaskDevice_Data.get_elementInfo(11))

    def get_SelectHubToName(self):
        """SELECT A SMART HUB page》获取Hub name"""
        return self.find_elements(*self.SelectHubToName_loc)

    # SELECT A SMART HUB page》获取Hub floor，room
    SelectHubToRoom_loc = (by.ID, TaskDevice_Data.get_elementInfo(12))

    def get_SelectHubToRoom(self):
        """SELECT A SMART HUB page》获取Hub floor，room"""
        return self.find_elements(*self.SelectHubToRoom_loc)

    # SELECT A SMART HUB page》获取hub的status，online、offline
    SelectHubToStatus_loc = (by.ID, TaskDevice_Data.get_elementInfo(13))

    def get_SelectHubToStatus(self):
        """SELECT A SMART HUB page》获取hub的status，online、offline"""
        return self.find_elements(*self.SelectHubToStatus_loc)

    def func_SelectHub(self):
        """
        添加zigbee时选择online 状态hub则跳转下个页面
        选择到offline设备时需要关闭弹框操作
        :return:
        """
        for index, row in enumerate(self.get_SelectHubToName()):
            time.sleep(5)
            LOG.info("添加zigbee设备时选择的hub({}-{})是{}状态。。。".format(row.text,
                                                               self.get_SelectHubToRoom()[index].text,
                                                               self.get_SelectHubToStatus()[index].text))
            row.click()
            if super().assertVisible_confirm():
                super().click_confirm()
            else:
                break  # 如果hub是online则跳出

    # SELECT A SMART STATION page》获取station 和station lite name
    SelectStationToName_loc = (by.ID, TaskDevice_Data.get_elementInfo(14))

    def get_SelectStationToName(self):
        """SELECT A SMART STATION page》获取station 和station lite name"""
        return self.find_elements(*self.SelectStationToName_loc)

    # SELECT A SMART STATION page》获取station 和station lite floor，room
    SelectStationToRoom_loc = (by.ID, TaskDevice_Data.get_elementInfo(15))

    def get_SelectStationToRoom(self):
        """SELECT A SMART STATION page》获取station 和station lite floor，room"""
        return self.find_elements(*self.SelectStationToRoom_loc)

    # SELECT A SMART STATION page》获取station 和 lite的status，online、offline
    SelectStationToStatus_loc = (by.ID, TaskDevice_Data.get_elementInfo(16))

    def get_SelectStationToStatus(self):
        """SELECT A SMART STATION page》获取station 和 lite的status，online、offline"""
        return self.find_elements(*self.SelectStationToStatus_loc)

    def func_SelectStation(self):
        """
        添加IR remote control时选择online 状态station则跳转下个页面
        选择到offline设备时需要关闭弹框操作添加
        :return:
        """
        for index, row in enumerate(self.get_SelectStationToName()):
            time.sleep(5)
            LOG.info("添加IR Remote时选择station({}-{})是{}状态》》》".format(row.text,
                                                                   self.get_SelectStationToRoom()[index].text,
                                                                   self.get_SelectStationToStatus()[index].text))
            row.click()
            if super().assertVisible_confirm():
                super().click_confirm()
            else:
                break  # 如果station是online则跳出

    def Add_hubPlugCurtain(self, hubPlugN):
        """
        function,
        添加Hub、Plug或curtain
        :param hubPlugN: Hub和plug在add device list page的索引号.固定
        """
        # 点击dashboard页面点击后跳转Add Device list page
        if hubPlugN == 0:
            super().func_clickAddDevice()  # 第一次执行点击Add Device控件。后续不点击
        self.get_AddListDeviceName()[hubPlugN].click()  # 根据索引号点击Hub、Plug或curtain
        if hubPlugN == 5:
            # Curtain，在select device page需要再次指定curtain索引号
            self.get_SelectDeviceToPair()[0].click()
        else:
            random.choice(self.get_SelectDeviceToPair()).click()  # 点击Smart hub或随机plug uk|us一行
        if hubPlugN == 2:
            # plug，则需要点击Warning 框的ok按钮
            super().click_button()
        super().click_confirm()  # wifi设备add device弹框的ok按钮
        LOG.info("‘LED is not blinking?’---%s" % self.func_GetNote())
        self.click_PairDeviceOK()  # 点击弹框的ok按钮,关闭弹框
        return self.func_ScanAndPair()

    def CloseBack(self, LoopN=2):
        """
        function,
        search wifi device关闭弹框后返回两次到list page
        :param LoopN:循环次数
        """
        super().click_ClosePopup()  # 点击search wifi device按钮后的弹框关闭按钮
        for i in range(LoopN):
            super().click_btnBack()

    def Add_GangSwitch(self, judge):
        """
        function,
        点击1|2|3 -gang light switch UK|US，Dimmer switch UK|US
        :param judge: 判断dimmer和switch的文案
        """
        if judge == "Gang Light Switch":
            self.get_AddListDeviceName()[1].click()  # 点击Switches一行
        rows = []
        for index, row in enumerate(self.get_SelectDeviceToPair()):
            if judge in row.text:
                rows.append(row)  # 提取出gang switch或这dimmer元素
                print(row.text)
        random.choice(rows).click()
        self.func_SelectHub()
        if judge == "Dimmer":
            super().click_button()  # Warning 框的ok按钮
        LOG.info("‘LED is not blinking?＇---%s" % self.func_GetNote())
        self.click_PairDeviceOK()  # 点击弹框的ok按钮,关闭弹框
        return self.func_ScanAndPair()

    def Add_SensorAndButton(self, ListPageN, SelectDeviceN):
        """function,
        添加there sensor和button
        :param ListPageN: add device list page的索引号
        :param SelectDeviceN: select Device to pair page的索引号
        """
        self.get_AddListDeviceName()[ListPageN].click()
        self.get_SelectDeviceToPair()[SelectDeviceN].click()  # 点击there sensor或button一行
        self.func_SelectHub()
        LOG.info("‘LED is not blinking?’》%s" % self.func_GetNote())
        self.click_PairDeviceOK()  # 点击弹框的ok按钮,关闭LED not弹框
        return self.func_ScanAndPair()

    def ConfirmBack(self, LoopN=2):
        """
        function,
        zigbee添加过程页面，点击返回弹框的ok按钮，后返回两次到list page
        :param LoopN: 点击次数
        """
        super().func_backConfirm()  # zigbee添加过程页面，点击返回弹框的ok按钮
        for i in range(LoopN):
            super().click_btnBack()

    def Add_WifiDevice(self, ListPageN, SelectDeviceN):
        """
        function,
        添加Add Device list pages添加3.5kw High Power Switch、Roller Blind、Ceiling light、Station和Station lite
        :param ListPageN: add device list page的索引号
        :param SelectDeviceN: select Device to pair page的索引号
        """
        self.get_AddListDeviceName()[ListPageN].click()
        self.get_SelectDeviceToPair()[SelectDeviceN].click()
        if SelectDeviceN == 4:
            super().click_button()  # 如果是3.5kw High Power Switch，则点击Warning 框的ok按钮
        super().click_confirm()  # wifi设备add device弹框的ok按钮
        LOG.info("‘LED is not blinking?’》%s" % self.func_GetNote())
        self.click_PairDeviceOK()  # 点击弹框的ok按钮,关闭弹框
        return self.func_AddDeviceSearch()

    # 滑动Add device list page页面
    AvailableDevices_loc = (by.ID, TaskDevice_Data.get_elementInfo(19))

    def swipe_DevicesListP(self):
        """滑动Add device list page页面"""
        gesture_mainpulation().swipe_up(self.driver, self.find_element(*self.AvailableDevices_loc))

    def Add_StationIR(self):
        """
        function,
        添加IR Remote Control
        :return:
        """
        self.swipe_DevicesListP()
        self.get_AddListDeviceName()[-2].click()  # 点击IR Remote Control一行
        self.func_SelectStation()
